<?php
/**
 * Created by PhpStorm.
 * User: ttl
 * Date: 2019/5/19
 * Time: 14:35
 */

namespace app\common\logic;
use think\Db;
use think\Validate;

class UserLogic
{
    public function user_getopenid(){
        $code = input('code');
        $secret = config('AppSecret');
        $appid = config('AppId');
        $get_openid_url = config('GETOPENIDURL');
        $GetOpenidUrl = str_replace(['APPID','SECRET','CODE'],[$appid,$secret,$code],$get_openid_url);

        if(strlen($code)>60){
            return ['status'=>'-1','msg'=>'code 有误','result'=>[]];
        }

        $backdb = http_get($GetOpenidUrl);

        if(!isset($backdb['openid'])){
            return ['status'=>'-1','msg'=>'获取微信openid失败','result'=>$backdb];
        }

        $openid = $backdb['openid'];
        $uid = 0;
        $res  =Db::name('users')->where(['openid'=>$openid])->field("uid,openid,token,expire")->find();
        $token_id = 0;
        $expire_time = 0;
        if(empty($res)){
            $savedata = [];
            $savedata['openid'] = $openid;
            $savedata['nick_name'] = '';
            $uid = Db::name('users')->insertGetId($savedata);
        }
        else{
            $uid = $res['uid'];
            $token = $res['token'];
            if($token) {
                $token_id = $token;
                $expire_time = $res['expire'];
                //如果过期
                if (time() > $expire_time) {
                    $token_id = 0;
                }
            }
        }

        if(!$token_id){
            $create_time = time();
            $expire_time = $create_time + (int)config('OVERDUE_TIME');
            $token_id = substr(md5($create_time.mt_rand(1000,9999)), 0,16);

            $add_num = Db::name('users')->update(['token'=>$token_id,'expire'=>$expire_time])->where(['uid'=>$uid]);
            if($add_num<1){
                return ['status'=>'-1','msg'=>'存储token 失败','result'=>[]];
            }
        }
        return ['status'=>'1','msg'=>'','result'=>['token'=>$token_id,'expire_time'=>$expire_time,'cur_time'=>time()]];
    }


    public function update_user($user){
        $userinfo = input('post.');

        $rule = [
            'nick_name'  => 'require|max:60',
            'head_icon'   => 'require|max:150',
        ];

        $msg = [
            'nick_name.require' => '请先授权',
            'nick_name.length'     => '名称最多不能超60个字符',
            'head_icon.require'   => '请先授权',
            'head_icon.length'  => '头像路径有误'
        ];

        $validate = new Validate($rule, $msg);
        $result   = $validate->check($userinfo);
        if(!$result){
            return ['status'=>'-1','msg'=>$validate->getError()];
        }

        Db::name('users')->where(['uid'=>$user['uid']])
            ->update(['nick_name'=>$userinfo['head_icon'],'head_icon'=>$userinfo['head_icon']]);

        return ['status'=>'1','msg'=>'修改成功'];
    }
}